//---------------------------------------------------------------------------

#ifndef __DatagramSocket_H
#define __DatagramSocket_H

//---------------------------------------------------------------------------
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
#define __MAGUS_WIN32
#include <winsock2.h>    
typedef SOCKET sock_t;
#else   // posix comptiable
#define _REENTRANT
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
#include <fcntl.h>
typedef int sock_t;
#endif  

namespace 
{
    const int HOSTNAME_LEN = 64;
}
//---------------------------------------------------------------------------

class DatagramSocket
{
private:
    void close();

public:
    DatagramSocket();
    ~DatagramSocket();

    // send data
    int connect(const char *host, int port);
    int send(const char *buf, int len);
    int send(const struct sockaddr *sa, const char *buf, int len);
    
    // receive data
    int listen(int port);
    int recv(char *buf, int len);

    int setTimeout(int timeout);
    int getTimeout() { return _M_timeout; }
    
    char *getHostName();
    char *getHostAddress();

    int getPort() { return _M_port; }
    int getFd() { return _M_fd; }
    sockaddr_in getInetAddress() { return _M_dest; }
    int getAddress() { return _M_dest.sin_addr.s_addr; }

    int getMyAddress();
    
    static int getInetAddressOf(const char *host, sockaddr_in *sa);
private:
    sock_t          _M_fd;
    sockaddr_in     _M_dest;
    int             _M_port;
    int             _M_timeout;
    char            _M_hostname[HOSTNAME_LEN];
};

//---------------------------------------------------------------------------

#endif  /* !__DatagramSocket_H */

